#!/bin/bash
# nacos 快捷docker安装运行
function nacosTemp() {
	echo "=========================================================="
	echo "========================nacos============================="
	echo "=========================================================="
	nacos_user="nacos_user"
	nacos_user_password="nacos"
	nacos_config="nacos_config"
	
	container_name="${asName}"
	container_ip=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "${container_name}")
	echo "Container IP: $container_ip"

	echo docker exec -i "${asName}" mysql -h$container_ip -uroot -p$MYSQL_ROOT_PASSWORD  -e "DROP DATABASE IF EXISTS $nacos_config;"
	echo docker exec -i "${asName}" mysql -h$container_ip -uroot -p$MYSQL_ROOT_PASSWORD  -e "CREATE DATABASE $nacos_config CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
	echo docker exec -i "${asName}" mysql -h$container_ip -uroot -p$MYSQL_ROOT_PASSWORD -e "CREATE USER '${nacos_user}'@'%' IDENTIFIED BY '${nacos_user_password}';"
	echo docker exec -i "${asName}" mysql -h$container_ip -uroot -p$MYSQL_ROOT_PASSWORD $nacos_config < nacos_config.sql
	
	docker exec -i "${asName}" mysql -h$container_ip -uroot -p$MYSQL_ROOT_PASSWORD  -e "DROP DATABASE IF EXISTS $nacos_config;"
	docker exec -i "${asName}" mysql -h$container_ip -uroot -p$MYSQL_ROOT_PASSWORD  -e "CREATE DATABASE $nacos_config CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
	docker exec -i "${asName}" mysql -h$container_ip -uroot -p$MYSQL_ROOT_PASSWORD -e "CREATE USER '${nacos_user}'@'%' IDENTIFIED BY '${nacos_user_password}';"
	docker exec -i "${asName}" mysql -h$container_ip -uroot -p$MYSQL_ROOT_PASSWORD $nacos_config < nacos_config.sql
	echo "=========================================================="
	echo "nacos 数据库预留nacos_config  用户名:${nacos_user} 密码:${nacos_user_password}"
	echo "=========================================================="
}

# 创建目录并移动脚本的函数
function createStart() {
    local dockerVolumes="$1"
    local name="$2"
    local scriptName="${name}.sh"
    local destination="/${dockerVolumes}/${name}/"
    rm -rf "${destination}"
    # 为脚本添加执行权限
    chmod +x "${scriptName}"

    # 使用 mkdir -p 创建父目录（如果不存在）
    mkdir -p "${destination}"

    # 删除已存在的脚本文件
    [ -f "/${dockerVolumes}/${name}/${scriptName}" ] && rm -rf "/${dockerVolumes}/${name}/${scriptName}"

    # 在移动之前检查脚本文件是否存在
    if [ -f "${scriptName}" ]; then
        cp "${scriptName}" "/${dockerVolumes}/${name}/"
		#nacos_config
        echo "脚本 '${scriptName}' 已复制到 '/${dockerVolumes}/${name}/'"
    else
        echo "错误：当前目录中找不到脚本 '${scriptName}'"
        exit 1
    fi
}

function dockerCreateStart() {
     name="$1"
     version="$2"
     asName="$3"
     portMap=$4
     volumesMap=$5
     dockerMap=$6
     copyDockerMap=$7
     lastDockerMap=$8

    # 取消注释以下一行，如果想要拉取 Docker 镜像
    #docker pull "${name}:${version}"

    # 删除同名容器
    docker rm -f "${asName}" &>/dev/null

    dockerRun="docker run"
    dockerRunTemp="docker run"

    # 添加端口映射参数
    for element in "${portMap[@]}"; do
        dockerRun+=" -p $element"
        dockerRunTemp+=" -p $element"
    done

    # 添加其他 Docker 参数
    for element in "${dockerMap[@]}"; do
        dockerRun+=" $element"
        dockerRunTemp+=" $element"
    done

    # 添加卷映射参数
    for element in "${volumesMap[@]}"; do
        dockerRun+=" -v $element"
        # dockerRunTemp+=" -v $element"
    done

    dockerRun+=" ${name}:${version}"
    dockerRunTemp+=" ${name}:${version}"

    #for element in "${lastDockerMap[@]}"; do
    #    dockerRun+=" $element"
    #    dockerRunTemp+=" $element"
    #done
    echo "$dockerRunTemp " #${name}:${version}
    $dockerRunTemp #"${name}:${version}"

    echo "复制 开始"
       # 复制 Docker 映射文件
    for element in "${copyDockerMap[@]}"; do
        echo "复制 $element"
        IFS=':' read -r source dest <<< "$element"
        echo "docker cp ${asName}:${source} ${dest}"
        docker cp "${asName}":"${source}" "${dest}"
    done

    echo "复制 完成"
      # 删除同名容器
    docker rm -f "${asName}" &>/dev/null
    echo "正式启动挂载"
    echo "$dockerRun " #${name}:${version}
    $dockerRun #"${name}:${version}"

    #read -r -p "查看 $name 运行日志?【Y/N】" input
    #if[ "$input,," =~ ^(YES|Y)$ ];then
    #    docker logs -f -t ${asName}
    #else
    #    echo ""
    #fi

}

function main(){
    # 默认值
    networkName="common-network"
    dockerVolumes="docker-volumes"
    #镜像名
    name="nacos/nacos-server"
    #别名
    asName="nacos"
    #版本
    version="v2.1.1"
    port="8848"
    hostPort="8848"
    portMap=("$hostPort:$port" "9848:9848" "9849:9849")
    #挂载地址
    v0="/etc/localtime:/etc/localtime"
    v1="/$dockerVolumes/$asName/conf:/home/nacos/conf"
    v2="/$dockerVolumes/$asName/logs:/home/nacos/logs"
    v3="/$dockerVolumes/$asName/data:/home/nacos/data "
    volumesMap=("$v0" "$v1" "$v2" "$v3")
    MYSQL_USER=nacos_user #"nacos_user " #root #非root报错 数据源未设置 原因mysql用户的问题 已解决需要用户允许远程和本地连接
    MYSQL_PASSWORD=nacos #"nacos" #root
    MYSQL_SERVICE_HOST=mysql8
    SPRING_DATASOURCE_PLATFORM=mysql
    MYSQL_SERVICE_PORT=3306
    MYSQL_SERVICE_DB_NAME=nacos_config
    MYSQL_SERVICE_DB_PARAM="characterEncoding=utf8&connectTimeout=40000&socketTimeout=60000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true"
    #环境配置
    dockerMap=("--restart=always" "-d")
    dockerMap+=("--privileged=true")
    dockerMap+=("--network=${networkName}")
    dockerMap+=("-e JVM_XMS=256m")
    dockerMap+=("-e JVM_XMX=256m")
    dockerMap+=("-e MODE=standalone")
    dockerMap+=("-e SPRING_DATASOURCE_PLATFORM=$SPRING_DATASOURCE_PLATFORM")
    dockerMap+=("-e MYSQL_SERVICE_HOST=$MYSQL_SERVICE_HOST")
    dockerMap+=("-e MYSQL_SERVICE_PORT=$MYSQL_SERVICE_PORT")
    dockerMap+=("-e MYSQL_SERVICE_DB_PARAM=$MYSQL_SERVICE_DB_PARAM")
    dockerMap+=("-e MYSQL_SERVICE_DB_NAME=$MYSQL_SERVICE_DB_NAME")
    dockerMap+=("-e MYSQL_SERVICE_USER=$MYSQL_USER")
    dockerMap+=("-e MYSQL_SERVICE_PASSWORD=$MYSQL_PASSWORD")
    dockerMap+=("--name=${asName}")

    lastDockerMap=("--character-set-server=utf8mb4")
    lastDockerMap+=("--collation-server=utf8mb4_unicode_ci")
    #容器地址:宿主机地址
    cp1="/home/nacos:/$dockerVolumes/"
    copyDockerMap=("$cp1" )
    #-v $PWD/mysql/conf:/etc/mysql/conf.d \
    #-v $PWD/mysql/logs:/logs \
    #-v $PWD/mysql/data:/var/lib/mysql \
    #-e MYSQL_ROOT_PASSWORD=root \
    echo "============================================="
    echo "       ${asName} Docker 安装启动前验证         "

    read -r -p "确认需要nacos依赖的MySQL数据库已执行 nacos_config.sql 文件否则无法启动nacos？ [y/N] " input1
    if [[ "${input1,,}" =~ ^(yes|y)$ ]]
    then
        echo ""
    else
        echo "请nacos依赖的MySQL数据库执行 nacos_config.sql 好文件后，再次运行该脚本！"
        exit 0
    fi


    echo "============================================="
    # 输出关于设置的信息
    echo "============================================="
    echo "        ${asName} Docker 安装挂载启动          "
    echo "============================================="
    docker network create "$networkName"
    # 使用 createStart 函数创建挂载目录
    echo "创建挂载目录..."
    createStart "${dockerVolumes}" "${asName}" 

    # 使用 dockerCreateStart 函数运行 Docker 容器
    dockerCreateStart "${name}" "${version}" "${asName}" $portMap $volumesMap $dockerMap $copyDockerMap #$lastDockerMap 

    echo "============================================="
    echo "        ${name} Docker 安装挂载启动成功         "
    echo "============================================="
    for element in "${volumesMap[@]}"; do
    echo "        ${asName} Docker 挂载目录：            "
        echo ${element}
    done
    echo "============================================="
}

main